#!/usr/bin/poython3.6
# conding:utf-8
from utils import getlogger
from .storage import Storage
import uuid

log = getlogger('handler')


class Handler(object):
    def __init__(self):
        self.store = Storage()

    def send(self, msg):  # 定义一个可调用的基础函数,此处的msg及就是对应的函数
        log.info('客户端agent发送消息为:{}'.format(msg))
        try:
            if msg['type'] in {'hearbeat', 'register'}:
                payload = msg['payload']
                info = {'hostname': payload['hostname'], 'ip': payload['ip']}
                self.store.reg_hb(payload['id'], info)
                log.info("客户端数据列表为:{}".format(self.store.agents))  # 客户端的列表
                return "agent信息为: {}".format(msg)
            elif msg['type'] == "result":  # 此处用于处理相关返回信息
                self.store.add_result(msg['payload'])  # 此处的msg返回的是
        except Exception  as e:
            log.error("注册客户端信息错误为:{}".format(e))
            return "Bad  Request...."

    def add_task(self, task):  # 此处用于在webserver 端创建的agent调用方法返回结果
        task['task_id'] = uuid.uuid4().hex  # 用于生成相关的任务id
        return self.store.add_task(task)  # 此处用于调用相关配置

    def get_agents(self):
        return self.store.get_agents()

    def get_task(self, agent_id):
        return self.store.get_task(agent_id)

    def get_result(self, task_id):  # 此处返回对应的值
        return self.store.get_result(task_id)


if __name__ == "__main__":
    pass
